package cn.hom1.exception;

import cn.hom1.model.enums.ResponseStatus;
import cn.hom1.model.vo.ResponseVo;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author iksen
 * @date 2019-01-16 16:03
 */
@ControllerAdvice
public class GlobalExceptionHandler {

  private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

  /**
   * 全局异常捕捉处理
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(value = Exception.class)
  public String defaultErrorHandler(Exception e, HttpServletRequest request){
    request.setAttribute("javax.servlet.error.status_code",ResponseStatus.ERROR.getCode());
    logger.error("系统发生异常！错误信息打印："+e.getMessage());
    return "forward:/error";
  }

  /***
   * 自定义常捕捉处理
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(value = MyException.class)
  @ResponseBody
  public ResponseVo MyHandler(Exception e, HttpServletRequest request){
    request.setAttribute("javax.servlet.error.status_code",ResponseStatus.ERROR.getCode());
    logger.error("系统发生异常！错误信息打印："+e.getMessage());
    return new ResponseVo(ResponseStatus.ERROR.getCode(),"系统发生异常！错误信息打印："+e.getMessage());
  }


}
